import React, { useRef, useEffect, useState } from 'react'
/** 交互组件 */
import {
    /** XFlow核心组件 */
    XFlow,
    /** 流程图画布组件 */
    FlowchartCanvas,
    /** 流程图配置扩展 */
    FlowchartExtension,
    /** 流程图节点组件 */
    FlowchartNodePanel,
    /** 流程图表单组件
     * 内置表单组件，用于节点、边、群组等样式和数据绑定，
     * 包括常用的标签、位置、尺寸、字号等，可通过 FlowchartFormPanel 快速自定义。
     */
    FlowchartFormPanel,
    FormItemWrapper,
    FlowchartFormWrapper,
    /** 通用组件：快捷键 */
    KeyBindings,
    /** 通用组件：画布缩放 */
    CanvasScaleToolbar,
    /** 通用组件：右键菜单 */
    CanvasContextMenu,
    /** 通用组件：工具栏 */
    CanvasToolbar,
    /** 通用组件：对齐线 */
    CanvasSnapline,
    /** 通用组件：节点连接桩 */
    CanvasNodePortTooltip,
    /** 生存uuid-36字符 */
    uuidv4,
} from '@antv/xflow'
/** 配置Command*/
import { useCmdConfig } from './config-cmd'
/** 配置Menu */
import { useMenuConfig } from './config-menu'
/** 配置Toolbar */
import { useToolbarConfig } from './config-toolbar'
/** 配置快捷键 */
import { useKeybindingConfig } from './config-keybinding'
/** 配置Dnd组件面板 */
import {
    CustomNode1
} from './react-node/index';
import JsonSchemaFormPart from './JsonSchemaForm';
import {
    RenameService,
    CanvasService,
} from './JsonSchemaForm/components';
import CCButton from './button';

import styles from './index.less';
import '@antv/xflow/dist/index.css';

import type { IAppLoad } from '@antv/xflow'
import type { Graph } from '@antv/x6'
import type { XFlowChartCanvasProps, XFlowProps, FlowPageProps } from '@/types/flow'

const XFlowChartCanvas = FlowchartCanvas as React.FC<XFlowChartCanvasProps>;
const XFlowChore = XFlow as React.FC<XFlowProps>;

export const FlowPage: React.FC<FlowPageProps> = props => {
    const { meta } = props
    const toolbarConfig = useToolbarConfig()
    const menuConfig = useMenuConfig()
    const keybindingConfig = useKeybindingConfig()
    const graphRef = useRef<Graph>()
    const commandConfig = useCmdConfig()
    /**
     * @param app 当前XFlow工作空间
     * @param extensionRegistry 当前XFlow配置项
     */

    const onLoad: IAppLoad = async app => {
        console.log('类型说明：图编辑应用', app);
        /** 获取画布实例 */
        graphRef.current = await app.getGraphInstance();
    }

    useEffect(() => {
        if (graphRef.current) {
            graphRef.current.on('node:click', (...arg) => {
                console.log('节点：被点击', arg)
            })
        }
    }, [graphRef])

    const controlMapService = controlMap => {
        controlMap.set('rename-service', RenameService)
        controlMap.set('canvas-service', CanvasService)
        return controlMap
    }

    const formSchemaService = async args => {
        const { targetType } = args
        const isGroup = args?.targetData?.isGroup
        const nodeSchema = {
            tabs: [
                {
                    name: '设置',
                    groups: [
                        {
                            name: 'groupName',
                            controls: [
                                {
                                    label: '节点名',
                                    name: '自定义form',
                                    shape: 'rename-service',
                                },
                            ],
                        },
                    ],
                },
            ],
        }
        if (isGroup) {
            // TODO
        }
        if (targetType === 'edge') {
            // TODO
        }
        if (targetType === 'node') {
            return nodeSchema
        }
        return {
            tabs: [
                {
                    name: '设置',
                    groups: [
                        {
                            name: 'groupName',
                            controls: [
                                {
                                    label: '',
                                    name: 'canvas-service',
                                    shape: 'canvas-service',
                                },
                            ],
                        },
                    ],
                },
            ],
        }
    }

    return (
        <>
            <XFlowChore
                className={styles['flow-user-custom-clz']}
                /** 在这里配置命令的hook */
                commandConfig={commandConfig}
                /** app 初始化成功的回调 */
                onLoad={onLoad}
                /** XFlow 工作台组件元信息, 会储存在全局Model中并在调用Service时作为额外的参数传入 */
                meta={meta}
                graphData={{
                    nodes: [],
                    edges: [],
                }}
            >
                <CCButton />
                {/* 流程图配置扩展-左侧的通用面板、自定义节点 */}
                <FlowchartExtension />
                {/* 流程图表单组件 */}
                {/* <FlowchartFormPanel
                    show={true}
                    position={{ width: 200, top: 40, bottom: 0, right: 0 }}
                    controlMapService={controlMapService}
                    formSchemaService={formSchemaService}
                /> */}
                <JsonSchemaFormPart />
                {/* 流程图节点组件 */}
                <FlowchartNodePanel
                    show={true}
                    showHeader={true}
                    showOfficial={true}
                    registerNode={[
                        {
                            key: 'cutsom-1',
                            title: '自定义节点-1',
                            nodes: [
                                {
                                    component: CustomNode1,
                                    popover: () => <div>自定义节点-1</div>,
                                    name: 'custom-node-indicator',
                                    width: 120,
                                    height: 50,
                                    label: '自定义节点-1',
                                },
                            ],
                        },
                        {
                            key: 'cutsom-2',
                            title: '自定义节点-2',
                            nodes: [
                                {
                                    component: CustomNode1,
                                    popover: () => <div>自定义节点-2</div>,
                                    name: 'custom-node-indicator',
                                    width: 120,
                                    height: 50,
                                    label: '自定义节点-2',
                                },
                            ],
                        }
                    ]}
                    position={{ width: 162, top: 40, bottom: 0, left: 0 }}
                />
                {/* 通用组件：工具栏 */}
                <CanvasToolbar
                    className={styles['xflow-workspace-toolbar-top']}
                    layout="horizontal"
                    config={toolbarConfig}
                    position={{
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                    }}
                />
                {/* 通用组件：快捷键 */}
                <KeyBindings
                    config={keybindingConfig}
                />
                {/* 流程图画布组件 */}
                <XFlowChartCanvas
                    showPortsOnNodeSelected={false}
                    config={{
                        /** 画布网格 */
                        grid: true,
                        /** 画布缩放等级 */
                        scaling: {
                            min: 0.2,
                            max: 3,
                        },
                        /** 画布滚轮缩放 */
                        mousewheel: {
                            enabled: true,
                            /** 将鼠标位置作为中心缩放 */
                            zoomAtMousePosition: true,
                        },
                        /** 画布宽度，默认使用容器宽度。 */
                        // width: 675,
                        /** 画布高度，默认使用容器高度。 */
                        height: 558,
                    }}
                    position={{
                        top: 40,
                        left: 0,
                        right: 0,
                        bottom: 0,
                    }}
                    // edgeConfig
                    useConfig={(config) => {

                    }}
                    onAddNode={(node) => {
                        console.log('新增节点时回调', node);

                    }}
                    onAddEdge={(edge) => {
                        console.log('新增边时回调', edge);
                    }}
                    onConfigChange={(params) => {
                        console.log('节点或边更新数据时调用', params);
                    }}
                >
                    {/* 通用组件：画布缩放 */}
                    <CanvasScaleToolbar
                        layout="horizontal"
                        position={{ top: -40, right: 0 }}
                        style={{
                            width: 150,
                            left: 'auto',
                            height: 39,
                        }}
                    />
                    {/* 通用组件：右键菜单 */}
                    <CanvasContextMenu
                        config={menuConfig}
                    />
                    {/* 通用组件：对齐线 */}
                    <CanvasSnapline
                        color="#faad14"
                    />
                    {/* 通用组件：节点连接桩 */}
                    <CanvasNodePortTooltip />
                </XFlowChartCanvas>
            </XFlowChore>
        </>
    )
}

export default FlowPage